package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.lagou.sqlSession.SqlSession;
import com.lagou.sqlSession.SqlSessionFactory;
import com.lagou.sqlSession.SqlSessionFactoryBuilder;
import org.dom4j.DocumentException;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.InputStream;
import java.util.List;

/*
 * 该类主要是提供该框架基础的初始化操作配置类
 *
 * 1、首先该类提供简单的加载操作
 * 2、该类需要对于配置文件进行流获取操作
 * 3、对于核心基础类进行封装调用
 * @Author 潘一
 */
public class IPersistenceInitConfig {

    private static IPersistenceInitConfig iPersistenceInitConfig;

    private Configuration configuration;

    private IPersistenceInitConfig(){

    }

    /*
     * 获取配置文件并初始化
     */
    private SqlSession init() throws PropertyVetoException, DocumentException {
        String resourcePath = File.separator+"config.xml";
        InputStream inputStream = Resources.getResourceAsSteam(resourcePath);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory.openSession();
    }

    public static SqlSession initConfig() {
        if(iPersistenceInitConfig==null) {
            iPersistenceInitConfig = new IPersistenceInitConfig();
            try {
                return iPersistenceInitConfig.init();
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public Configuration getConfiguration(){
        return configuration;
    }
}
